﻿/*
 * TempMeter.cs
 * 
 * 热释电红外传感器
 * 
 * By developer_ken
 */

using System;
using System.IO.Ports;
using System.Threading;

namespace SmGateDemo
{
    public class TempMeter : ISensor
    {
        SerialPort Port;
        Thread SerialThread;
        bool DEBUG;
        public TemperatureResult Temperature { get; private set; }

        public struct TemperatureResult
        {
            public float Raw;
            public float Calibrated;
            public DateTime TimeOfMeasurement;
        }

        public TempMeter(string port)
        {
            DEBUG = Environment.GetEnvironmentVariable("SMG_DEBUG") != null && Environment.GetEnvironmentVariable("SMG_DEBUG").Length > 0;
            Port = new SerialPort(port, 9600);
            Port.Open();
            SerialThread = new Thread(new ThreadStart(() => { while (true) { ReadSensor(); } }));
        }

        public void Init()
        {
            SerialThread.Start();
        }

        public static string[] GetPorts()
        {
            return SerialPort.GetPortNames();
        }

        private void ReadSensor()
        {
            int fbyte;
            do
            {
                fbyte = Port.ReadByte();
                if (DEBUG)
                {
                    string hex = String.Format("{0:X}", fbyte);
                    Console.WriteLine("[TTL]<NON>" + hex);
                }
            } while (fbyte != 0x55);//找到起始位置
            fbyte = Port.ReadByte();
            if (DEBUG)
            {
                string hex = String.Format("{0:X}", fbyte);
                Console.WriteLine("[TTL]<1>" + hex);
            }
            if (fbyte != 0xAA) return;//格式不对，取消操作
            var result = new TemperatureResult();
            int byte1 = Port.ReadByte(); if (DEBUG) { string hex = String.Format("{0:X}", byte1); Console.WriteLine("[TTL]<R-t1a>" + hex); }
            int byte2 = Port.ReadByte(); if (DEBUG) { string hex = String.Format("{0:X}", byte2); Console.WriteLine("[TTL]<R-t1b>" + hex); }
            result.Calibrated = (byte1 * 16 * 16 + byte2) / 100f;
            int byte3 = Port.ReadByte(); if (DEBUG) { string hex = String.Format("{0:X}", byte3); Console.WriteLine("[TTL]<R-t2a>" + hex); }
            int byte4 = Port.ReadByte(); if (DEBUG) { string hex = String.Format("{0:X}", byte4); Console.WriteLine("[TTL]<R-t2b>" + hex); }
            result.Raw = (byte3 * 16 * 16 + byte4) / 100f;
            int verify = Port.ReadByte();//校验位读掉 
            if (DEBUG) { string hex = String.Format("{0:X}", verify); Console.WriteLine("[TTL]<R-crc>" + hex); }
            result.TimeOfMeasurement = DateTime.Now;
            Temperature = result;
        }
    }
}
